#!/bin/bash

set -e

if [[ -n "${RF_DEBUG}" ]]; then
    set -x
fi

if [[ -n "${GIT_COMMIT}" ]]; then
    GIT_COMMIT="${GIT_COMMIT:0:7}"
else
    GIT_COMMIT="$(git rev-parse --short HEAD)"
fi

DIR="$(dirname "$0")"

function usage() {
    echo -n \
        "Usage: $(basename "$0")
Build application for staging or release.
"
}

if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
    if [ "${1:-}" = "--help" ]; then
        usage
    else
        echo "Pulling down configuration settings for test environment"

        ./scripts/bootstrap --env
        # ./scripts/bootstrap --sbtopts
        ./scripts/load_development_data --download

        echo "Building JARs (batch, api)"
        docker-compose \
            -f "${DIR}/../docker-compose.test.yml" \
            run --rm --no-deps \
            build "; batch/assembly; api/assembly"

        cp "${DIR}/../app-backend/batch/target/scala-2.12/batch-assembly.jar" \
            "${DIR}/../app-tasks/jars/batch-assembly.jar"

        echo "Building Batch container image"
        GIT_COMMIT="${GIT_COMMIT}" docker-compose \
            -f "${DIR}/../docker-compose.yml" \
            -f "${DIR}/../docker-compose.test.yml" \
            build batch

        echo "Running tests"
        GIT_COMMIT="${GIT_COMMIT}" ./scripts/test
        echo "All tests pass!"
    fi
fi
